package com.afdor.rws.core.extension.utils;

import com.afdor.rws.annotation.extension.Extension;
import com.afdor.rws.core.extension.ExtensionItem;
import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.ConstructorUtils;

import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.List;

/**
 * 工具类
 *
 * @author 悭梵
 * @date Created in 2018-09-06 17:54
 */
public class ExtensionUtils {
    /**
     * 得到扩展点的全名称
     *
     * @param name
     * @return
     */
    public static final String getFullExtension(@NonNull Class typeClass, @NonNull String name) {
        if (!StringUtils.startsWith(name, typeClass.getPackage().getName())) {
            if (StringUtils.endsWith(name, typeClass.getSimpleName())) {
                return new StringBuilder(100).append(typeClass.getPackage().getName()).append(".").append(name).toString();
            } else {
                return new StringBuilder(100).append(typeClass.getPackage().getName()).append(".").append(name).append(typeClass.getSimpleName()).toString();
            }
        }
        return name;
    }

    /**
     * 根据@Extension.order()对指定列表中的Extension对象排序
     *
     * @param extensionList
     */
    public static final <T> void orderExtensionByClass(List<ExtensionItem<T>> extensionList) {
        if (extensionList != null && extensionList.size() > 1) {
            Collections.sort(extensionList, (leftItem, rigthItem) -> {
                Extension leftExtension = leftItem == null || leftItem.getExtensionClass() == null ? null : leftItem.getExtensionClass().getAnnotation(Extension.class);
                Extension rigthExtension = rigthItem == null || rigthItem.getExtensionClass() == null ? null : rigthItem.getExtensionClass().getAnnotation(Extension.class);

                int orderLeftNum = (leftExtension == null ? Extension.NORMAL_ORDER : leftExtension.order());
                int orderRightNum = (rigthExtension == null ? Extension.NORMAL_ORDER : rigthExtension.order());

                return orderLeftNum == orderRightNum ? 0 : orderRightNum - orderLeftNum;
            });
        }
    }

    /**
     * 根据@Extension.order()对指定列表中的Extension对象排序
     *
     * @param extensionInstanceList
     */
    public static final <T> void orderExtensionByInstance(List<?> extensionInstanceList) {
        if (extensionInstanceList != null && extensionInstanceList.size() > 1) {
            Collections.sort(extensionInstanceList, (leftItem, rigthItem) -> {
                Extension leftExtension = leftItem == null ? null : leftItem.getClass().getAnnotation(Extension.class);
                Extension rigthExtension = rigthItem == null ? null : rigthItem.getClass().getAnnotation(Extension.class);

                int orderLeftNum = (leftExtension == null ? Extension.NORMAL_ORDER : leftExtension.order());
                int orderRightNum = (rigthExtension == null ? Extension.NORMAL_ORDER : rigthExtension.order());

                return orderLeftNum == orderRightNum ? 0 : orderRightNum - orderLeftNum;
            });
        }
    }

    /**
     * 根据入参数量及类型，获取对应的构造器
     *
     * @param clazz       实现类
     * @param argsClasses 构造参数
     * @return
     */
    public static final <T> Constructor<T> getExtensionConstructorByParameters(Class<T> clazz, Class<?>[] argsClasses) {
        if (clazz.isAnnotation() || clazz.isInterface() || clazz.isEnum() || Modifier.isAbstract(clazz.getModifiers())) {
            return null;
        }
        Constructor<T> constructor = ConstructorUtils.getAccessibleConstructor(clazz, argsClasses);
        if (constructor == null) {
            Constructor<T>[] constructores = (Constructor<T>[]) clazz.getDeclaredConstructors();
            for (Constructor<T> item : constructores) {
                /* 参数个数一致 */
                if (item.getParameterTypes().length == argsClasses.length) {
                    Class<?>[] parameterTypes = item.getParameterTypes();
                    boolean isThisConstructor = true;
                    for (int i = 0, length = argsClasses.length; i < length; i++) {
                        // 继承关系判断
                        if (!parameterTypes[i].isAssignableFrom(argsClasses[i])) {
                            isThisConstructor = false;
                            break;
                        }
                    }
                    if (isThisConstructor) {
                        constructor = item;
                        break;
                    }
                }
            }
        }
        return constructor;
    }
}
